package com.example.xianji.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.R;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.CustomProgressDialog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;


import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter.ViewBinder;

public class Main_GeRen_RenZhengActivity extends Activity implements OnClickListener {
    private GridView geren_renzheng_gridview;

    private ArrayList<HashMap<String, Object>> imageItem;
    private SimpleAdapter simpleAdapter;
    private LinearLayout layout;
    private ListView show_listview;
    private PopupWindow show_popupWindow;
    private String group[] = new String[]{"手机相册", "拍照", "取消"};
    private String path;
    private File file;
    private ArrayList<Bitmap> tupian = new ArrayList<Bitmap>();
    private Bitmap bitmap;
    private ImageView geren_renzheng_back;
    //    private SharedPreferences sp;
//    private Editor ed;
    private Button shenqing_renzheng;
    private String photoStr;
    private CustomProgressDialog mCustomProgressDialog;
    private TextView text_shangchuang_name;
    private Handler handle = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
            }
        }
    };

    /**
     * 二进制转字符串
     *
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) {
        StringBuffer sb = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                sb.append("0" + stmp);
            } else {
                sb.append(stmp);
            }
        }
        return sb.toString();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main__ge_ren__ren_zheng);
        //MyApplication.getInstance().addActivity(this);
        geren_renzheng_gridview = (GridView) findViewById(R.id.geren_renzheng_gridview);

        geren_renzheng_back = (ImageView) findViewById(R.id.geren_renzheng_back);

        text_shangchuang_name = (TextView) findViewById(R.id.text_shangchuang_name);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        if (PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TYPE, "").equals("FC")
                || PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TYPE, "").equals("AC")) {
//        if (sp.getString("xianji_type", "").equals("FC") || sp.getString("xianji_type", "").equals("AC")) {
            text_shangchuang_name.setText("请上传营业执照");

        } else {
            text_shangchuang_name.setText("请上传身份证");

        }
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.paishe);

        shenqing_renzheng = (Button) findViewById(R.id.shenqing_renzheng);

        imageItem = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("itemImage", bitmap);
        imageItem.add(map);
        simpleAdapter = new SimpleAdapter(this,
                imageItem, R.layout.griditem_addpic,
                new String[]{"itemImage"}, new int[]{R.id.imageView1});

        simpleAdapter.setViewBinder(new ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data,
                                        String textRepresentation) {
                if (view instanceof ImageView && data instanceof Bitmap) {
                    ImageView i = (ImageView) view;
                    i.setImageBitmap((Bitmap) data);
                    return true;
                }
                return false;
            }
        });
        geren_renzheng_gridview.setAdapter(simpleAdapter);

        geren_renzheng_gridview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                if (imageItem.size() == 2) {
                    Toast.makeText(Main_GeRen_RenZhengActivity.this, "上传一张身份证正面就可以了哦", Toast.LENGTH_SHORT).show();
                }
                if (position == 0) {
                    Photo_show();
                    show_popupWindow.showAtLocation(findViewById(R.id.shangchuang), Gravity.BOTTOM, 0, 0);
                    show_listview.setAdapter(new ArrayAdapter<String>(Main_GeRen_RenZhengActivity.this, R.layout.information_show_photo_item, R.id.show_photo_item_text, group));

                    show_listview.setOnItemClickListener(new OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1,
                                                int arg2, long arg3) {
                            if (group[arg2].equals("手机相册")) {
                                show_popupWindow.dismiss();
                                /*Intent intent=new Intent(Intent.ACTION_PICK, null);
                                 *//**
                                 * 下面这句话，与其它方式写是一样的效果，如果：
                                 * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                 * intent.setType(""image/*");设置数据类型
                                 * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
                                 * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀？有什么区别？
                                 *//*
										intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
										startActivityForResult(intent, 1);*/

                                //相册
                                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                startActivityForResult(intent, 1);
                                Log.i("5555555", "5555555");
                            }
                            if (group[arg2].equals("拍照")) {
                                show_popupWindow.dismiss();
                                /**
                                 * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方
                                 * 文档，you_sdk_path/docs/guide/topics/media/camera.html
                                 * 我刚看的时候因为太长就认真看，其实是错的，这个里面有用的太多了，所以大家不要认为
                                 * 官方文档太长了就不看了，其实是错的，这个地方小马也错了，必须改正
                                 *//*
										Log.i("6666666666", "66666666");
										Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
										intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
												.fromFile(new File(Environment
														.getExternalStorageDirectory(),
														"xiaoma.jpg")));
							 			startActivityForResult(intent, 2);*/

                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                                startActivityForResult(intent, 2);
                            }
                            if (group[arg2].equals("取消")) {
                                show_popupWindow.dismiss();

                            }
                        }
                    });


                }
            }
        });

        geren_renzheng_gridview.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                           int arg2, long arg3) {
                if (arg2 != 0) {
                    dialog(arg2);
                }
                return true;
            }
        });

        geren_renzheng_back.setOnClickListener(this);
        shenqing_renzheng.setOnClickListener(this);
    }

    protected void dialog(final int position) {
        Builder builder = new Builder(Main_GeRen_RenZhengActivity.this);
        builder.setMessage("确认移除已添加图片吗?");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                imageItem.remove(position);
                simpleAdapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case 1:
                    Uri selectedImage = data.getData();
                    String[] filePathColumns = {MediaStore.Images.Media.DATA};
                    Cursor c = this.getContentResolver().query(
                            selectedImage, filePathColumns, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    String picturePath = c.getString(columnIndex);// 取出图片路径
                    c.close();
                    Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
                    show(bitmap);
                    break;
                case 2:
                    Bitmap bitmap1 = (Bitmap) data.getExtras().get("data");
                    show(bitmap1);
                case 3:
                    /**
                     * 非空判断大家一定要验证，如果不验证的话，
                     * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                     * 当前功能时，会报NullException，小马只
                     * 在这个地方加下，大家可以根据不同情况在合适的
                     * 地方做判断处理类似情况
                     */
                    if (data != null) {
                        setPicToView(data);
                    }
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "false");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 650);
        intent.putExtra("outputY", 650);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
        String[] pojo = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, pojo, null, null, null);
        if (cursor != null) {
            ContentResolver cr = this.getContentResolver();
            int colunm_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            path = cursor.getString(colunm_index);
            if (path.endsWith("jpg") || path.endsWith("png")) {
                String picPath = path;
                file = new File(picPath);
            }
        }
    }

    /**
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        Bitmap photo = null;
        if (extras != null) {
            photo = extras.getParcelable("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG, 100, stream);// (0 - 100)压缩文件
            byte[] bt = stream.toByteArray();
            photoStr = byte2hex(bt);
            // list.add( photoStr);

            // tupian.add(photo);
            imageItem.clear();
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("itemImage", photo);
            imageItem.add(map);

            simpleAdapter = new SimpleAdapter(this,
                    imageItem, R.layout.griditem_addpic,
                    new String[]{"itemImage"}, new int[]{R.id.imageView1});
            simpleAdapter.setViewBinder(new ViewBinder() {
                @Override
                public boolean setViewValue(View view, Object data,
                                            String textRepresentation) {
                    if (view instanceof ImageView && data instanceof Bitmap) {
                        ImageView i = (ImageView) view;
                        i.setImageBitmap((Bitmap) data);
                        return true;
                    }
                    return false;
                }
            });
            geren_renzheng_gridview.setAdapter(simpleAdapter);
            simpleAdapter.notifyDataSetChanged();
        }
    }

    public void show(Bitmap photo) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.PNG, 100, stream);// (0 - 100)压缩文件
        byte[] bt = stream.toByteArray();
        photoStr = byte2hex(bt);
        // list.add( photoStr);

        // tupian.add(photo);
        imageItem.clear();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("itemImage", photo);
        imageItem.add(map);

        Log.i("5555555555555", imageItem.size() + "");
        simpleAdapter = new SimpleAdapter(this,
                imageItem, R.layout.griditem_addpic,
                new String[]{"itemImage"}, new int[]{R.id.imageView1});
        simpleAdapter.setViewBinder(new ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data,
                                        String textRepresentation) {
                if (view instanceof ImageView && data instanceof Bitmap) {
                    ImageView i = (ImageView) view;
                    i.setImageBitmap((Bitmap) data);
                    return true;
                }
                return false;
            }
        });
        geren_renzheng_gridview.setAdapter(simpleAdapter);
        simpleAdapter.notifyDataSetChanged();
    }

    private void Photo_show() {
        layout = (LinearLayout) LayoutInflater.from(
                Main_GeRen_RenZhengActivity.this).inflate(
                R.layout.information_shoow_photo, null);
        show_listview = (ListView) layout.findViewById(R.id.information_photo_listview);
        show_listview.setCacheColorHint(0);
        show_popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setBackgroundDrawable(new BitmapDrawable());
        show_popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        show_popupWindow.update();
        show_popupWindow.setOutsideTouchable(true);
        show_popupWindow.setFocusable(true);
        show_popupWindow.setContentView(layout);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.geren_renzheng_back) {
            this.finish();
        } else if (v.getId() == R.id.shenqing_renzheng) {
            if (photoStr.length() == 0) {
            } else {
                mCustomProgressDialog = CustomProgressDialog.createDialog(Main_GeRen_RenZhengActivity.this);
                mCustomProgressDialog.setCanceledOnTouchOutside(false);
                mCustomProgressDialog.show();
                renzheng();
            }
        }
    }


    public void renzheng() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("cert", photoStr);
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
//        parms.addBodyParameter("token", sp.getString("xianji_token", ""));
        httpUtils.send(HttpMethod.POST, Contant.renzheng, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                handle.sendEmptyMessage(1);
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                Log.i("qqqqqqqq", arg0.result);
                JSONObject object;
                try {
                    object = new JSONObject(arg0.result);
                    Toast.makeText(Main_GeRen_RenZhengActivity.this, object.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (object.getInt("status") == 1) {
                        Contant.renzheng_success = 1;
                        Main_GeRen_RenZhengActivity.this.finish();
                    }

                    handle.sendEmptyMessage(1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handle.removeCallbacksAndMessages(null);
    }
}
